// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
const db = uniCloud.database()
const dbCmd = db.command
module.exports = {
	async detail(_id) {
		let now = Date.now()
		let goodsRes =  db.collection('goods').doc(_id).get()
		let commentRes =  db.collection('comment').where({
			goods_id:_id
		}).get()
		let couponRes = db.collection('coupon').where({
			// 没有超期 有剩余
			available:dbCmd.gt(0),
			start:dbCmd.lt(now),
			end:dbCmd.gt(now)
		}).get()
		let skuRes = db.collection('goods-sku').where({
			goods_id:_id
		}).get()
		return {
			goods:(await goodsRes).data[0],
			comments:(await commentRes).data,
			coupon:(await couponRes).data,
			sku:(await skuRes).data
		}
	},
	
	sku(_id) {
		return db.collection('goods-sku').where({
			goods_id: _id
		}).get()
	},
	async payGoods(list = []) {
		if (list.length == 1) {
			let goods, attr;
			const elem = list[0];
			// 属性长度 长度大于0 判断属性库存是否足够 为0时判断商品库存是否足够
			if (elem.attr_id.length > 0) {
				let resAttr = await db.collection('goods-sku').where({
					_id:elem.attr_id
				}).get()
				if (resAttr.data[0].stock > 0) {
					return {
						affectedDocs: 1,
						data: [true]
					}
				} else {
					return {
						affectedDocs: 0,
						data: [false]
					}
				}
			} else {
				let resGoods = await db.collection('goods').limit(1).where({
					_id: elem.goods_id
				}).get();
				if (resGoods.data[0].remain_count > 0) {
					return {
						affectedDocs: 1,
						data: [true]
					}
				} else {
					return {
						affectedDocs: 0,
						data: [false]
					}
				}
			}

			return goods;
		}else if(list.length>1){
			for(let i=0;i<list.length;i++){
				// TODO 判断商品库存是否足够
			}
		}else{
			return {
				affectedDocs: 0,
				data: []
			}
		}
	},
	coupon() {
		return db.collection('coupon').get()
	},
	getcoupon(uid, coupon) {
		return new Promise((resolve, reject) => {
			db.collection('user_coupon').where({
				coupon_id: coupon._id
			}).get().then(res => {
				if (res.affectedDocs > 0) {
					reject({
						errMsg: "已领取优惠券",
						errCode: 1
					})
				} else {
					db.collection('user_coupon').add({
						user_id: uid,
						coupon_id: coupon._id,
						is_use: false,
						condition: coupon.condition,
						reason: coupon.reason,
						value: coupon.value,
						name: coupon.name,
						start_at: coupon.startAt,
						end_at: coupon.endAt,
						value_desc: coupon.valueDesc,
						unit_desc: coupon.unitDes
					}).then(res => {
						resolve(res)
					})
				}
			})
		})

	}
}
